<template>
	<div class="mqtt_user_span">
		<table-span
            :current-page="tabelData.current"
            :page-size="tabelData.size"
            :total="tabelData.total"
            :isShowTool="false"
            :isShowPagePlug="false" 
            :size-change="handleSizeChange"
            :current-change="handleCurrentChange">
            <template v-slot:searchItem>
                <div class="search_item_span search_item_fix_width">
                    <el-input size="default" v-model="searchCondition.clientId"
                        placeholder="请输入客户端ID" clearable></el-input>
                    
                </div>
                <div class="search_item_span search_item_fix_width">
                    <el-input size="default" v-model="searchCondition.username"
                        placeholder="请输入用户名" clearable></el-input>
                </div>
            	<div class="search_item_span">
                    <el-button icon="Search" size="default" type="primary" @click="searchData">查询</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Plus" size="default"
                        type="primary" :disabled="!(btOption.btMqttUserSave)"
                        @click="btSaveData">新增数据</el-button>
                </div>
            </template>
            <template v-slot:searchTable>
            	<el-table :data="tabelData.records" size="default" height="100%" style="width: 100%;">
                    <el-table-column align="center" type="index" width="50">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="clientId"
                        label="客户端ID"
                        min-width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="username"
                        label="用户名"
                        min-width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="createTime"
                        label="创建时间"
                        min-width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="online"
                        label="状态"
                        width="120">
                        <template #default="scope">
                            <el-text type="success" v-if="scope.row.online == 1">在线</el-text>
                            <el-text type="danger" v-else>离线</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" align="center" label="操作" width="240">
                        <template #default="scope">
                            <el-button size="small" :disabled="!(btOption.btMqttUserUpdate)"
                                @click="btUpdateData(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="small" :disabled="!(btOption.btMqttUserReset)"
                                @click="btResetPassword(scope.$index, scope.row)">重置密码</el-button>
                            <el-button size="small" type="danger" :disabled="!(btOption.btMqttUserDelete)"
                                @click="btDeleteData(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </table-span>
        <el-dialog :title="dataDialogOption.title" v-model="dataDialogOption.isShow" @close="dataDialogClose"
            :before-close="dataDialogBeforeClose" :close-on-click-modal="false"
            :close-on-press-escape="false" width="420px">
            <el-form ref="dataFormRef" :model="dataForm" :rules="dataFormRules" label-width="110px" size="default">
                <el-form-item label="客户端Id" prop="clientId">
                    <el-input v-model="dataForm.clientId" placeholder="请填写客户端Id" :clearable="true" :disabled="dataDialogOption.type == 1"></el-input>
                </el-form-item>
                <el-form-item label="客户端名称" prop="username">
                    <el-input v-model="dataForm.username" placeholder="请填写客户端名称" :clearable="true"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="default" @click="dataDialogCancel">取 消</el-button>
                <el-button size="default" type="primary" @click="dataDialogConfirm">确认</el-button>
            </template>
        </el-dialog>
	</div>
</template>
<script>
import { h } from 'vue'
import TableSpan from '@/components/table-span.vue';
import {tool} from "@/js/tool.js";
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
	name: "MqttUser",
	data: function(){
		return {
			btOption: {
				btMqttUserSave: null,
                btMqttUserUpdate: null,
                btMqttUserDelete: null,
                btMqttUserReset: null,
                btMqttUserExport: null
			},
			tabelData: {
	            total: 0,
	            size: 10,
	            current: 1,
	            records: []
            },
            searchCondition: {
                clientId: null,
                username: null,
            	page: 1,
            	size: 10
            },
            dataDialogOption: {
            	type: 0, //0新增；1修改
            	title: '',
            	isShow: false,
                selectRow: null
            },
            dataForm: {
                mainId: null,
            	clientId: null,
                username: null
            },
            dataFormRules: {
            	clientId: [
                    { required: true, message: '请填写客户端Id', trigger: 'blur' },
                    { max: 30, message: '客户端Id不能超过30个字符', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请填写客户端名称', trigger: 'blur' },
                    { max: 30, message: '客户端名称不能超过30个字符', trigger: 'blur' }
                ]
            }
		}
	},
	methods: {
		searchData: function(){
			this.searchCondition.page = this.tabelData.current;
			this.searchCondition.size = this.tabelData.size;
        	getDataList(this);
        },
        handleSizeChange: function(size){
            this.searchCondition.size = size;
            this.searchCondition.page = 1;
            getDataList(this);
        },
        handleCurrentChange: function(current){
            this.searchCondition.page = current;
            getDataList(this);
        },
        btSaveData: function(){
        	this.dataDialogOption.title = "新增数据";
            this.dataDialogOption.type = 0;
            this.dataDialogOption.isShow = true;
        },
        btUpdateData: function(index, row){
        	this.dataDialogOption.title = "更新数据";
            this.dataDialogOption.type = 1;
            this.dataDialogOption.isShow = true;
            this.dataDialogOption.selectRow = row;
            
            this.dataForm.mainId = row.mainId;
            this.dataForm.clientId = row.clientId;
            this.dataForm.username = row.username;

        },
        btDeleteData: function(index, row){
        	const confirmMessage = "是否删除:"+ row.clientId +"？";
            const obj = this;
            this.$confirm(confirmMessage).then(function () {
                //执行数据删除
                const param = {
                    mainId: row.mainId
                }
                deleteData(obj, param);
            }).catch(function () {});
        },
        btResetPassword: function(index, row){
            this.dataDialogOption.selectRow = row;
            const confirmMessage = "是否重置:"+ row.clientId +"密码？";
            const obj = this;
            this.$confirm(confirmMessage).then(function () {
                const param = {
                    mainId: row.mainId
                }
                resetPassword(obj, param);
            }).catch(function () {});
        },
        dataDialogBeforeClose: function(){
        	dialogCloseTips(this);
        },
        dataDialogClose: function(){
            this.dataForm.mainId = null;
            this.dataForm.clientId = null;
            this.dataForm.username = null;
        	this.$refs["dataFormRef"].clearValidate();
        },
        dataDialogCancel: function(){
        	dialogCloseTips(this);
        },
        dataDialogConfirm: function(){
        	const obj = this;
        	this.$refs["dataFormRef"].validate(function(valid) {
                if(valid){
                    if(obj.dataDialogOption.type == 0){
                        //新增
                        saveData(obj);
                    }else{
                        //更新
                        updateData(obj);
                    }
                }else{
                    return false;
                }
            });
        }
	},
	created: function(){
	    const menuId = [this.$route.query.menuId]
	    const obj = this;
	    new tool.getAuthorisedRequest(menuId, this.btOption, function(){
	    	getDataList(obj);
	    });
    },
    components: {
    	TableSpan
    }
}

/**
* 获取数据信息列表
*/
function getDataList(app){
	const param = app.searchCondition;
	const url = "/iot/mqttUser/list";
    tool.formJsonRequest(url,param,null,function(data){
        if(data.code === "0000"){
            app.tabelData.total = data.data.total;
            app.tabelData.size = data.data.size;
            app.tabelData.current = data.data.current;
            app.tabelData.records = data.data.records;
        }else{
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存数据信息
 */
function saveData(app){
	const param = app.dataForm;
    const url = "/iot/mqttUser/save";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDataList(app);
            app.dataDialogOption.isShow = false;
            showPasswordTips(data.data.clientId, data.data.password);
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存文档信息
 */
function updateData(app){
    const param = app.dataForm;
    const url = "/iot/mqttUser/update";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDataList(app);
            app.dataDialogOption.isShow = false;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 删除数据信息
 */
function deleteData(app, param){
    const url = "/iot/mqttUser/delete";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getDataList(app);
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 重置客户端密码
 */
 function resetPassword(app, param){
    const row = app.dataDialogOption.selectRow
    const url = "/iot/mqttUser/resetPassword";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            showPasswordTips(row.clientId, data.data.password);
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 重置密码提示信息
 */
function showPasswordTips(clientId, password){
    ElMessageBox(
        {
            message: h('p', null, [
                h('p', { style: 'font-size: 18px; margin-bottom: 5px' }, '客户端clientId:' + clientId),
                h('p', { style: 'color: #F56C6C; font-size: 22px' }, password)
            ]),
            title: '客户端密码不能进行查询，请妥善保存',
            showCancelButton: true,
            confirmButtonText: '复制',
            cancelButtonText: '关闭',
        }
    ).then(() => {
        navigator.clipboard.writeText(password)
        .then(() => {
            ElMessage({
                showClose: true,
                message: '复制成功',
                type: 'success'
            });
        })
        .catch(() => {
            ElMessage({
                showClose: true,
                message: '复制失败',
                type: 'error'
            });
        })
    }).catch(() => {

    })
}

/**
 * 关闭dialog的提示信息
 * @param app
 */
function dialogCloseTips(app) {
    var confirmMessage = "";
    if (app.dataDialogOption.type == 0) {
        confirmMessage = "是否放弃新增数据信息？";
    } else {
        confirmMessage = "是否放弃修改数据信息？";
    }
    var obj = app;
    app.$confirm(confirmMessage).then(function () {
        obj.dataDialogOption.isShow = false;
    }).catch(function () { });
}
</script>
<style>
.mqtt_user_span{
    position: relative;
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
    font-family: Microsoft YaHei,Heiti SC,tahoma,arial,Hiragino Sans GB,"\5B8B\4F53",sans-serif;
}
.search_item_span{
    max-width: 190px;
    height: auto;
    margin-top: 5px;
	margin-left: 10px;
}
.search_item_fix_width {
    width: 190px;
}
</style>
